package com.cinema.dao;

import com.cinema.entity.Cinema;
import com.cinema.util.DBUtil;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 影院数据访问对象
 */
public class CinemaDAO {
    
    /**
     * 获取所有影院列表
     */
    public List<Cinema> findAll() {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<Cinema> cinemas = new ArrayList<>();
        
        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT * FROM cinemas WHERE status = 'ACTIVE' ORDER BY name";
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();
            
            while (rs.next()) {
                Cinema cinema = mapResultSetToCinema(rs);
                cinemas.add(cinema);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, rs);
        }
        
        return cinemas;
    }
    
    /**
     * 根据ID获取影院
     */
    public Cinema findById(Integer id) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        Cinema cinema = null;
        
        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT * FROM cinemas WHERE id = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, id);
            rs = pstmt.executeQuery();
            
            if (rs.next()) {
                cinema = mapResultSetToCinema(rs);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, rs);
        }
        
        return cinema;
    }
    
    /**
     * 将ResultSet映射为Cinema对象
     */
    private Cinema mapResultSetToCinema(ResultSet rs) throws SQLException {
        Cinema cinema = new Cinema();
        cinema.setId(rs.getInt("id"));
        cinema.setName(rs.getString("name"));
        cinema.setAddress(rs.getString("address"));
        cinema.setCity(rs.getString("city"));
        cinema.setDistrict(rs.getString("district"));
        cinema.setPhone(rs.getString("phone"));
        cinema.setFacilities(rs.getString("facilities"));
        cinema.setStatus(rs.getString("status"));
        cinema.setCreatedAt(rs.getTimestamp("created_at"));
        cinema.setUpdatedAt(rs.getTimestamp("updated_at"));
        return cinema;
    }
}
